/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import { Form, Input, DatePicker, message, Button, Tabs, InputNumber, Radio, Select } from 'antd';
import {connect} from 'dva';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { Vector } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import Feature from 'ol/Feature';
import { Icon, Stroke, Style } from 'ol/style';
import Point from 'ol/geom/Point';
import { fromLonLat, toLonLat } from 'ol/proj';

import xfs from './../../images/xfs-blue.png';
import yali from './../../images/press.png';
import axios from 'axios';
import GeoJSON from 'ol/format/GeoJSON';
import setting from '../ValveFlowMeterSIte/setting.json';
const { TabPane } = Tabs;
const Option = Select.Option;
import styles from '../ValveFlowMeterSIte/index.less';
import find from 'lodash/find';
//星图地球地图
import { get as getProjection } from 'ol/proj'
import { getTopLeft, getWidth } from 'ol/extent'
import TileGrid from 'ol/tilegrid/TileGrid'
const projection = getProjection('EPSG:3857')
const matrixIds = []
const tileSizePixels = 256
const tileSizeMtrs = getWidth(projection.getExtent()) / tileSizePixels
const resolutions = []
for (let i = 0; i <= 18; i++) {
  matrixIds[i] = i
  resolutions[i] = tileSizeMtrs / Math.pow(2, i)
}
const tileGrid = new TileGrid({
  origin: getTopLeft(projection.getExtent()),
  resolutions: resolutions,
  matrixIds: matrixIds,
})

const FormItem = Form.Item;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      area_id:localStorage.getItem('area_id')?localStorage.getItem('area_id'):'6901726763131338752',
      all_vendors:[],
      all_protocols:[],
      layers: [
        new TileLayer({
          title: '天地图卫星影像',
          visible: true,
          source: new XYZ({
            url: 'https://tiles1.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&tmsIds=w&token=6dd3767b369eb5b724937e4ad74b2e78e95ad67ac7bbc1049539cb0691ad6ca2',//星图地球
            tileGrid: tileGrid, // 星图地球指定切片的网格参数
          }),
        }),
        new TileLayer({
          title: '卫星标注',
          visible: true,
          source: new XYZ({
            url: 'https://tiles1.geovisearth.com/base/v1/cia/{z}/{x}/{y}?format=png&tmsIds=w&token=6dd3767b369eb5b724937e4ad74b2e78e95ad67ac7bbc1049539cb0691ad6ca2',//星图地球
            tileGrid: tileGrid, // 星图地球指定切片的网格参数
          }),
        }),

      ],
      point:[],
      pipeData:[],
      templateId: this.props.templateId,
      pointImg:xfs,
      hardware_configs: {},
    };
  }
  getMarker=()=>{
    return this.state.point
  }
  getConfig = () => {
    return {
      template: this.state.templateId,
      hardware_configs: this.state.hardware_configs,
    };
  };
  componentDidMount() {
    const that=this;
    const response = setting;
    console.log('hd_response', response);
    if (!this.props.editRecord) {
      console.log('response', response);
      response.data.hardware_configs.modbus_03 = response.data.hardware_configs.modbus;
      response.data.hardware_configs.flowmeter = [{},{}];
      this.setState({
        hardware_configs: response.data.hardware_configs,
      },function() {
        if(this.state.templateId===602601){//602601流量计
          this.state.hardware_configs.device[0].enable = 1;
          this.state.hardware_configs.flowmeter[0].enable = 1;
          this.state.hardware_configs.flowmeter[0].alias = '流量计';
          this.state.hardware_configs.flowmeter[0].device_number = '';
          this.state.hardware_configs.flowmeter[0].valve_status = 0;
          this.state.hardware_configs.flowmeter[0].upload_interval = 12 ;
          this.setState({
            hardware_configs: this.state.hardware_configs,
          });
        }
        if(this.state.templateId===602602){//602601压力传感器
          this.state.hardware_configs.pressure_sensor[0].enable = 1;
          this.state.hardware_configs.pressure_sensor[0].alias = '压力传感器';
          this.setState({
            hardware_configs: this.state.hardware_configs,
          });
        }
      });
    } else {
      let editRecord = JSON.parse(JSON.stringify(this.props.editRecord));
      console.log('this.props.editRecord', editRecord);
      editRecord.hardware_configs.modbus_03 = editRecord.hardware_configs.modbus;

      if(this.state.templateId===602601){//602601流量计
        editRecord.hardware_configs.device[0].upload_interval = editRecord.hardware_configs.device[0].upload_interval / 60;
      }
      this.setState({
        hardware_configs: editRecord.hardware_configs,
      });
    }

    if (this.props.findChildFunc) {
      this.props.findChildFunc(this.getMarker);
    }
    if (this.props.getConfigFunc) {
      this.props.getConfigFunc(this.getConfig);
    }
    let center=[118.24511238911211, 25.49622132293699]
    let map = this.map = new Map({
      target: 'press_sensor_map',
      layers: this.state.layers,
      view: new View({
        center: (this.props.editRecord&&this.props.editRecord.longitude)?fromLonLat([this.props.editRecord.longitude,this.props.editRecord.latitude]):fromLonLat(center),//
        zoom: 13,
        maxZoom: 21,
      }),
    });
    let pointerLayer=null;
    if(this.props.editRecord){
      this.setState({
        point:gcoord.transform(
          [this.props.editRecord.longitude,this.props.editRecord.latitude],    // 经纬度坐标
          gcoord.GCJ02,               // 当前坐标系
          gcoord.WGS84                 // 目标坐标系
        )
      },function() {
        let mockvectorSource=that.createApoint(fromLonLat(this.state.point))
        // 创建标注图层
        pointerLayer = new Vector({
          zIndex: 11,
          source: mockvectorSource,
        });
        // 将标注图层添加到地图上
        map.addLayer(pointerLayer);
      })
    }
    map.on('click', function(e) {
      //在点击时获取像素区域;
      console.log(toLonLat(e.coordinate));
      that.setState({
        point:toLonLat(e.coordinate)
      })
      if(pointerLayer){
        map.removeLayer(pointerLayer)
      }
      let mockvectorSource=that.createApoint(e.coordinate)
      // 创建标注图层
      pointerLayer = new Vector({
        zIndex: 11,
        source: mockvectorSource,
      });
      // 将标注图层添加到地图上
      map.addLayer(pointerLayer);
    })

  }
  createApoint=(coordinate)=>{
    let point = new Feature({
      geometry: new Point(coordinate),
      name: '压力传感器',
    });
    //设置图标的样式
    point.setStyle(new Style({
      /**{olx.style.IconOptions}类型*/
      image: new Icon({
        anchorOrigin: 'top-right',
        offsetOrigin: 'top-right',
        src: this.state.pointImg,
      })
    }));

    // 创建标注的数据源
    let mockvectorSource = new VectorSource({
      features: [point],
    });
    return mockvectorSource
  }
  changeConfig = (newConfig) => {
    this.setState({
      hardware_configs: { ...this.state.hardware_configs, ...newConfig },
    });
  };
  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 17},
      }
    };
    console.log(this.state.point)
    const {getFieldDecorator} = this.props.form;
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <FormItem
            style={{width:'50%',display:'inline-block'}}
            {...formItemLayoutWithLabel}
            label={(
              <span>
               消防栓编号
            </span>
            )}
          >
            {getFieldDecorator('number', {
              initialValue: this.props.editRecord ? this.props.editRecord.number : '',
              rules: [{ required: true, message: '请输入编号' }],
            })(
              <Input placeholder={'1001'} />
            )}
          </FormItem>
          <FormItem
            style={{width:'50%',display:'inline-block'}}
            {...formItemLayoutWithLabel}
            label={(
              <span>
              资产编号
            </span>
            )}
          >
            {getFieldDecorator('name', {
              initialValue: this.props.editRecord ? this.props.editRecord.name : '',
              rules: [{ required: true, message: '请输入资产编号' }],
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            style={{width:'50%',display:'inline-block'}}
            {...formItemLayoutWithLabel}
            label={(
              <span>
               消防栓IMEI
            </span>
            )}
          >
            {getFieldDecorator('imei', {
              initialValue: this.props.editRecord ? this.props.editRecord.imei : '',
              rules: [{ required: true, message: '请输入IMEI' }],
            })(
              <Input disabled={Boolean(this.props.editRecord)} />
            )}
          </FormItem>
          <FormItem
            style={{width:'50%',display:'inline-block'}}
            {...formItemLayoutWithLabel}
            label={(
              <span>
               安装地址
            </span>
            )}
          >
            {getFieldDecorator('address', {
              initialValue: this.props.editRecord ? this.props.editRecord.address: '',
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            style={{width:'50%',display:'inline-block'}}
            {...formItemLayoutWithLabel}
            label={(
              <span>
               标高
            </span>
            )}
          >
            {getFieldDecorator('elevation', {
              initialValue: this.props.editRecord ? this.props.editRecord.elevation: '',
            })(
              <Input />
            )}
          </FormItem>
          <FormItem
            style={{width:'50%',display:'inline-block'}}
            {...formItemLayoutWithLabel}
            label={(
              <span>
               描述
            </span>
            )}
          >
            {getFieldDecorator('description', {
              initialValue: this.props.editRecord ? this.props.editRecord.description: '',
            })(
              <Input />
            )}
          </FormItem>
          <div id="press_sensor_map" style={{width:'100%',height:'400px'}}></div>
        </Form>

        <div
          style={{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={this.props.onClose} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={()=>{
            if(this.state.point.length===0){
              message.error('请点击地图上选择一个点')
              return
            }
            this.props.onSave()
          }} type="primary">
            确定
          </Button>
        </div>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
